import {getRequest} from "./api";

/*初始化菜单*/
export const initMenu = (router, store) => {
    if (store.state.routes.length > 0) {
        return;
    }
    getRequest('/system/cfg/menu').then(data => {
        if (data) {
            //格式化Router
            let fmtRoutes = formatRoutes(data);
            //添加到Router
            router.addRoutes(fmtRoutes);
            //调用store/index.js中的方法，将数据存入vuex
            store.commit('initRoutes', fmtRoutes);
            //连接webSocket
            store.dispatch('connect');
        }
    })
};

export const formatRoutes = (routes) => {
    let fmtRoutes = [];
    routes.forEach(router => {
        let {
            path,
            component,
            name,
            iconCls,
            children,
        } = router;
        if (children && children instanceof Array) {
            //递归
            children = formatRoutes(children);
        }
        let fmRouter = {
            path: path,
            name: name,
            iconCls: iconCls,
            children: children,
            component(resolve) {
                //如果
                if (component.startsWith('Home')) {
                    require(['../views/' + component + '.vue'], resolve);
                } else {
                    //截取组件的前3位并且全部变为小写，以此来匹配包名
                    let start = component.slice(0, 3).toLowerCase();
                    require(['../views/' + start + '/' + component + '.vue'], resolve);
                }
            }
        };
        fmtRoutes.push(fmRouter)
    });
    return fmtRoutes;
};
